package com.stockz.downloaderx.bse;

import java.io.IOException;
import java.io.StringWriter;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipInputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.stockz.core.model.Bar;
import com.stockz.core.model.Exchange;
import com.stockz.downloaderx.AbstractBredthDownloader;

@Component
public class BseDownloader extends AbstractBredthDownloader{

	@Autowired
	@Qualifier("download.url.bse.start")
	private String downloadUrlBseStart = "http://www.bseindia.com/bhavcopy/eq";
	@Autowired
	@Qualifier("download.url.bse.end")
	private String downloadUrlBseEnd = "_csv.zip";
	@Autowired
	@Qualifier("download.url.bse.date.format")
	private String downloadUrlBseDateFormat = "ddMMyy";
	@Autowired
	private BseBarBredthCSVParser bseBarBredthCSVParser;
	
	public int getOrder() {
		return 0;
	}
	
	@Override
	public String constructUri(Date date) {
		DateFormat dateFormat = new SimpleDateFormat(downloadUrlBseDateFormat);
		String uri = downloadUrlBseStart + dateFormat.format(date) + downloadUrlBseEnd;
		return 	uri;
	}
	
	@Override
	public String downloadRawData(String uri) {
		String output = null;
		try{
			ZipInputStream inStream = new ZipInputStream(new URL(uri).openStream());
	        byte[] buffer = new byte[1024];
	        int nrBytesRead;
	        StringWriter w = new StringWriter();
	        if (inStream.getNextEntry() != null) {
	            while ((nrBytesRead = inStream.read(buffer)) > 0) {
	            	w.write(new String(buffer,0,nrBytesRead));
	            }
	        }
	        w.flush();
	        w.close();
	        inStream.close();
			output = w.toString();
		}catch(IOException ie){
			output = "";
		}
		return output;
	}
	
	@Override
	public List<Bar> parse(String text, Exchange exchange) {
		return bseBarBredthCSVParser.parseCsv(text,exchange.getCode());
	}
}
